package com.gufe.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.gufe.common.core.domain.entity.*;
import com.gufe.system.common.BaseSystemService;
import com.gufe.system.domain.BaseSystemOrg;
import com.gufe.system.domain.SysPost;
import com.gufe.system.domain.SysUserPost;
import com.gufe.system.domain.SysUserRole;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.gufe.common.constant.CacheConstants;
import com.gufe.common.constant.Constants;
import com.gufe.common.constant.UserConstants;
import com.gufe.common.core.domain.model.LoginUser;
import com.gufe.common.core.redis.RedisCache;
import com.gufe.common.exception.ServiceException;
import com.gufe.common.exception.user.BlackListException;
import com.gufe.common.exception.user.CaptchaException;
import com.gufe.common.exception.user.CaptchaExpireException;
import com.gufe.common.exception.user.UserNotExistsException;
import com.gufe.common.exception.user.UserPasswordNotMatchException;
import com.gufe.common.utils.DateUtils;
import com.gufe.common.utils.MessageUtils;
import com.gufe.common.utils.StringUtils;
import com.gufe.common.utils.ip.IpUtils;
import com.gufe.framework.manager.AsyncManager;
import com.gufe.framework.manager.factory.AsyncFactory;
import com.gufe.framework.security.context.AuthenticationContextHolder;
import com.gufe.system.service.ISysConfigService;
import com.gufe.system.service.ISysUserService;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Resource
    private RestTemplate restTemplate;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private BaseSystemService baseSystemService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try
        {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        finally
        {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 单点登录验证
     * @return 结果
     */
    public String ssoLogin(LoginUser loginUser)
    {
        // 1. 权限查询（必须！）
        loginUser.setPermissions(permissionService.getRolePermission(loginUser.getUser()));

        // 2. 记录登录成功日志（建议保留）
        AsyncManager.me().execute(
                AsyncFactory.recordLogininfor(
                        loginUser.getUsername(),
                        Constants.LOGIN_SUCCESS,
                        "SSO login success"
                )
        );

        // 3. 更新用户登录信息（重要！）
        recordLoginInfo(loginUser.getUserId());

        // 4. 生成Token（核心目标）
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha))
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }



    /**
     * 对字符串进行 MD5 加密，返回小写结果
     * @param input 明文字符串
     * @return 32位小写MD5值
     */
    public static String md5(String input) {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("输入不能为空");
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b & 0xff));
            }
            return sb.toString(); // 返回小写MD5
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }

    public LoginUser getLoginUser(String code) {

        // 1. 获取用户基本信息（含 roleIds, postIds）
        BaseSystemUser baseSystemUser = baseSystemService.getUserInfo(code).getData();
        if (baseSystemUser == null) {
            throw new RuntimeException("无法获取用户信息，code: " + code);
        }

        Long userId = baseSystemUser.getUserId();
        List<Long> roleIdsList = baseSystemUser.getRoleIds();
        List<Long> postIdsList = baseSystemUser.getPostIds();

        // 2. 获取全量组织数据
        BaseSystemOrg baseSystemOrg = baseSystemService.getSystemOrg().getData();
        if (baseSystemOrg == null) {
            throw new RuntimeException("无法获取系统组织信息");
        }

        List<SysUser> allUserList = baseSystemOrg.getSysUserList();
        List<SysRole> allRoleList = baseSystemOrg.getSysRoleList();
        List<SysDept> allDeptList = baseSystemOrg.getSysDeptList();
        List<SysPost> allPostList = baseSystemOrg.getSysPostList();

        // 3. 找到当前用户的完整信息
        SysUser fullUser = allUserList.stream()
                .filter(u -> userId.equals(u.getUserId()))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("未找到用户: " + userId));

        // 4. 构建 SysUser（合并基础信息 + 完整信息）
        SysUser sysUser = new SysUser();
        sysUser.setUserId(fullUser.getUserId());
        sysUser.setDeptId(fullUser.getDeptId());
        sysUser.setUserName(fullUser.getUserName());
        sysUser.setNickName(fullUser.getNickName());
        sysUser.setEmail(fullUser.getEmail());
        sysUser.setPhonenumber(fullUser.getPhonenumber());
        sysUser.setSex(fullUser.getSex());
        sysUser.setAvatar(fullUser.getAvatar());
        sysUser.setPassword(fullUser.getPassword());
        sysUser.setStatus(fullUser.getStatus());
        sysUser.setDelFlag(fullUser.getDelFlag());
        sysUser.setLoginIp(fullUser.getLoginIp());
        sysUser.setLoginDate(fullUser.getLoginDate());
        sysUser.setPwdUpdateDate(fullUser.getPwdUpdateDate());

        // ✅ 设置 roleIds 和 postIds（转为 Long[]）
        sysUser.setRoleIds(roleIdsList != null ? roleIdsList.toArray(new Long[0]) : new Long[0]);
        sysUser.setPostIds(postIdsList != null ? postIdsList.toArray(new Long[0]) : new Long[0]);

        // 5. 设置 dept（部门）
        if (sysUser.getDeptId() != null) {
            sysUser.setDept(allDeptList.stream()
                    .filter(d -> d.getDeptId().equals(sysUser.getDeptId()))
                    .findFirst()
                    .orElse(null));
        }

        // 6. 设置 roles（角色列表）
        if (roleIdsList != null && !roleIdsList.isEmpty()) {
            List<SysRole> roles = allRoleList.stream()
                    .filter(role -> roleIdsList.contains(role.getRoleId()))
                    .toList();
            sysUser.setRoles(roles);  // ✅ 关键：设置 roles 列表
        } else {
            sysUser.setRoles(List.of());
        }

        // 8. 构建 LoginUser
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(sysUser.getUserId());
        loginUser.setDeptId(sysUser.getDeptId());
        loginUser.setUser(sysUser);
        loginUser.setIpaddr(sysUser.getLoginIp());
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setPermissions(extractPermissions(sysUser.getRoles())); // 从角色中提取权限

        return loginUser;

    }
    private Set<String> extractPermissions(List<SysRole> roles) {
        if (roles == null) return new HashSet<>();
        return roles.stream()
                .map(SysRole::getRoleKey)  // 假设角色权限标识是 roleKey，如 "admin", "common"
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
    }
}
